import React, { useState, useEffect } from 'react';
import authService from '../services/authService';
import './Login.css';

const Login = ({ onLoginSuccess }) => {
  const [isLogin, setIsLogin] = useState(true);
  const [formData, setFormData] = useState({
    username: '',
    email: '',
    phone: '',
    hospital: '',
    position: '',
    customPosition: '',
    password: '',
    confirmPassword: ''
  });
  const [positions, setPositions] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');

  // 加载职位列表
  useEffect(() => {
    const loadPositions = async () => {
      const result = await authService.getPositions();
      if (result.success) {
        setPositions(result.data);
      }
    };
    loadPositions();
  }, []);

  const handleInputChange = (e) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));
    // 清除错误信息
    if (error) setError('');
  };

  const validateForm = () => {
    const { username, email, phone, hospital, position, password, confirmPassword } = formData;
    
    if (!username.trim()) {
      setError('请输入用户名');
      return false;
    }
    
    if (!isLogin) {
      if (!email.trim()) {
        setError('请输入邮箱地址');
        return false;
      }
      
      if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
        setError('请输入有效的邮箱地址');
        return false;
      }
      
      if (!phone.trim()) {
        setError('请输入手机号码');
        return false;
      }
      
      if (!/^1[3-9]\d{9}$/.test(phone)) {
        setError('请输入有效的手机号码');
        return false;
      }
      
      if (!hospital.trim()) {
        setError('请输入医院名称');
        return false;
      }
      
      if (!position) {
        setError('请选择职位');
        return false;
      }
      
      if (position === '其他' && !formData.customPosition?.trim()) {
        setError('请输入具体职位');
        return false;
      }
    }
    
    if (!password) {
      setError('请输入密码');
      return false;
    }
    
    if (!isLogin && password.length < 6) {
      setError('密码至少需要6个字符');
      return false;
    }
    
    if (!isLogin && password !== confirmPassword) {
      setError('两次输入的密码不一致');
      return false;
    }
    
    return true;
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    
    if (!validateForm()) return;
    
    setLoading(true);
    setError('');
    setSuccess('');
    
    try {
      if (isLogin) {
        // 登录
        const result = await authService.login({
          username: formData.username,
          password: formData.password
        });
        
        if (result.success) {
          setSuccess('登录成功！');
          // 立即调用登录成功回调，不要延迟
          onLoginSuccess();
        } else {
          setError(result.error);
        }
      } else {
        // 注册
        const finalPosition = formData.position === '其他' ? formData.customPosition : formData.position;
        const result = await authService.register({
          username: formData.username,
          email: formData.email,
          phone: formData.phone,
          hospital: formData.hospital,
          position: finalPosition,
          password: formData.password
        });
        
        if (result.success) {
          setSuccess('注册成功！请登录');
          setIsLogin(true);
          setFormData({
            username: formData.username,
            email: '',
            phone: '',
            hospital: '',
            position: '',
            customPosition: '',
            password: '',
            confirmPassword: ''
          });
        } else {
          setError(result.error);
        }
      }
    } catch (error) {
      setError('操作失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  const toggleMode = () => {
    setIsLogin(!isLogin);
    setFormData({
      username: '',
      email: '',
      phone: '',
      hospital: '',
      position: '',
      customPosition: '',
      password: '',
      confirmPassword: ''
    });
    setError('');
    setSuccess('');
  };

  return (
    <div className="login-container">
      <div className="login-card">
        <div className="login-header">
          <h1 className="login-title">APIViewer</h1>
          <p className="login-subtitle">医学图像查看器</p>
        </div>
        
        <div className="login-form-container">
          <div className="login-tabs">
            <button 
              className={`tab-button ${isLogin ? 'active' : ''}`}
              onClick={() => setIsLogin(true)}
            >
              登录
            </button>
            <button 
              className={`tab-button ${!isLogin ? 'active' : ''}`}
              onClick={() => setIsLogin(false)}
            >
              注册
            </button>
          </div>
          
          <form onSubmit={handleSubmit} className="login-form">
            <div className="form-group">
              <label htmlFor="username" className="form-label">用户名</label>
              <input
                type="text"
                id="username"
                name="username"
                value={formData.username}
                onChange={handleInputChange}
                className="form-input"
                placeholder="请输入用户名"
                required
              />
            </div>
            
            {!isLogin && (
              <>
                <div className="form-group">
                  <label htmlFor="email" className="form-label">邮箱</label>
                  <input
                    type="email"
                    id="email"
                    name="email"
                    value={formData.email}
                    onChange={handleInputChange}
                    className="form-input"
                    placeholder="请输入邮箱地址"
                    required
                  />
                </div>
                
                <div className="form-group">
                  <label htmlFor="phone" className="form-label">手机号码</label>
                  <input
                    type="tel"
                    id="phone"
                    name="phone"
                    value={formData.phone}
                    onChange={handleInputChange}
                    className="form-input"
                    placeholder="请输入手机号码"
                    required
                  />
                </div>
                
                <div className="form-group">
                  <label htmlFor="hospital" className="form-label">医院</label>
                  <input
                    type="text"
                    id="hospital"
                    name="hospital"
                    value={formData.hospital}
                    onChange={handleInputChange}
                    className="form-input"
                    placeholder="请输入医院名称"
                    required
                  />
                </div>
                
                <div className="form-group">
                  <label htmlFor="position" className="form-label">职位</label>
                  <select
                    id="position"
                    name="position"
                    value={formData.position}
                    onChange={handleInputChange}
                    className="form-select"
                    required
                  >
                    <option value="">请选择职位</option>
                    {positions.map((position) => (
                      <option key={position} value={position}>
                        {position}
                      </option>
                    ))}
                  </select>
                </div>
                
                {formData.position === '其他' && (
                  <div className="form-group">
                    <label htmlFor="customPosition" className="form-label">请输入具体职位</label>
                    <input
                      type="text"
                      id="customPosition"
                      name="customPosition"
                      value={formData.customPosition || ''}
                      onChange={handleInputChange}
                      className="form-input"
                      placeholder="请输入您的具体职位"
                      required
                    />
                  </div>
                )}
              </>
            )}
            
            <div className="form-group">
              <label htmlFor="password" className="form-label">密码</label>
              <input
                type="password"
                id="password"
                name="password"
                value={formData.password}
                onChange={handleInputChange}
                className="form-input"
                placeholder={isLogin ? "请输入密码" : "请输入密码（至少6个字符）"}
                required
              />
            </div>
            
            {!isLogin && (
              <div className="form-group">
                <label htmlFor="confirmPassword" className="form-label">确认密码</label>
                <input
                  type="password"
                  id="confirmPassword"
                  name="confirmPassword"
                  value={formData.confirmPassword}
                  onChange={handleInputChange}
                  className="form-input"
                  placeholder="请再次输入密码"
                  required
                />
              </div>
            )}
            
            {error && (
              <div className="error-message">
                <span className="error-icon">⚠️</span>
                {error}
              </div>
            )}
            
            {success && (
              <div className="success-message">
                <span className="success-icon">✅</span>
                {success}
              </div>
            )}
            
            <button 
              type="submit" 
              className="submit-button"
              disabled={loading}
            >
              {loading ? '处理中...' : (isLogin ? '登录' : '注册')}
            </button>
          </form>
          
          <div className="login-footer">
            <span className="toggle-text">
              {isLogin ? '还没有账号？' : '已有账号？'}
            </span>
            <button 
              type="button" 
              className="toggle-button"
              onClick={toggleMode}
            >
              {isLogin ? '立即注册' : '立即登录'}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};

export default Login; 